<?php 
//I.F. Nuevo: 2010-03-28; ramarin
require_once('../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/'.$CFG->admin.'/report/moosisca/managecategorieslib.php');
require_once($CFG->dirroot . '/course/lib.php');
//require_once($CFG->dirroot . '/course/request_form.php');

$systemcontext = get_context_instance(CONTEXT_SYSTEM);

if (!has_capability('report/moosisca:newspacerequest', $systemcontext)) {
	error('You do not have the required permission to request a new space.');
}

global $USER;

if ($frm = data_submitted() and confirm_sesskey()) {
  if(isset($frm->radCategory) && (isset($frm->txtCourseName) || isset($frm->cboCoursesWs))){  
    $courseName = (isset($frm->txtCourseName) && $frm->txtCourseName != '') ? $frm->txtCourseName : $frm->cboCoursesWs;
    
    $errors = validation($courseName);
    
    if($errors != ""){
      notice($errors);
    }
    
    $course = new stdClass();
    $course->shortname = $courseName;
    $course->fullname = (isset($frm->hidFullName) && $frm->hidFullName != '') ? $frm->hidFullName : $courseName;
    
/// Ensure all is well before proceeding.
    fix_course_sortorder();

/// Build up a course record based on the request.
    $course->category = $frm->radCategory;
    $course->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$course->category");
    if (empty($course->sortorder)) {
        $course->sortorder = 1000;
    }
    
    $teacherid = $USER->id;
    $course->requested = 1;
    $course->teacher = get_string("defaultcourseteacher");
    $course->teachers = get_string("defaultcourseteachers");
    $course->student = get_string("defaultcoursestudent");
    $course->students = get_string("defaultcoursestudents");
    if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
        $course->restrictmodules = 1;
    }

/// Apply course default settings
    $courseconfig = get_config('moodlecourse');
    $course->format = $courseconfig->format;
    $course->numsections = $courseconfig->numsections;
    $course->hiddensections = $courseconfig->hiddensections;
    $course->newsitems = $courseconfig->newsitems;
    $course->showgrades =  $courseconfig->showgrades;
    $course->showreports = $courseconfig->showreports;
    $course->maxbytes = $courseconfig->maxbytes;
    $course->timecreated = time();
    $course->timemodified = time();

/// Insert the record.
    if ($courseid = insert_record('course', $course)) {
      $page = page_create_object(PAGE_COURSE_VIEW, $courseid);
      blocks_repopulate_page($page); // Return value not checked because you can always edit later
      $context = get_context_instance(CONTEXT_COURSE, $courseid);
      role_assign($CFG->creatornewroleid, $teacherid, 0, $context->id); // assing teacher role
      $course->id = $courseid;
      
      if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { // if we're all or requested we're ok.
        $allowedmods = explode(',',$CFG->defaultallowedmodules);
        update_restricted_mods($course,$allowedmods);
      }
      
      //Insert the record to workflow
      $workflow = new stdClass();
      $workflow->courseid = $courseid;
      $workflow->space_type = $frm->cboSpaceType;
      $workflow->state = 'created';
      $workflow->userid = $USER->id;
      
      if($workflowid = insert_record('moosisca_workflow', $workflow)){
        $history = new stdClass();
        $history->workflowid = $workflowid;
        $history->state = 'created';
        $history->userid = $USER->id;
        $history->observations = '';
        $history->timecreated = time();
        
        if($historyid = insert_record('moosisca_workflow_history', $history)){
          $success = 1;
        }
        else{
          delete_record('moosisca_workflow', 'id', $workflowid);
        }
      }
      else{
        delete_record('course', 'id', $courseid);
      }
    }
    
    if (!empty($success)) {
      redirect($CFG->wwwroot.'/course/edit.php?id='.$courseid);

    } else {
      print_error('courseapprovedfailed', 'report_moosisca');
    }
    
    //request_add($frm->radCategory, $frm->$c1, $frm->cboSpaceType);
  }
}




class clsWSSEAuth {
          private $Username;
          private $Password; 
        function __construct($username, $password) {
                 $this->Username=$username;
                 $this->Password=$password;
              }
}

class clsWSSEToken {
        private $UsernameToken;
        function __construct ($innerVal){
            $this->UsernameToken = $innerVal;
        }
} 

$username = 'serviciosAcadem';
$password = 'Ws_2011_';

//Check with your provider which security name-space they are using.
$strWSSENS = "http://schemas.xmlsoap.org/ws/2002/07/secext";

$objSoapVarUser = new SoapVar($username, XSD_STRING, NULL, $strWSSENS, NULL, $strWSSENS);
$objSoapVarPass = new SoapVar($password, XSD_STRING, NULL, $strWSSENS, NULL, $strWSSENS); 

$objWSSEAuth = new clsWSSEAuth($objSoapVarUser, $objSoapVarPass); 
$objSoapVarWSSEAuth = new SoapVar($objWSSEAuth, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS); 
$objWSSEToken = new clsWSSEToken($objSoapVarWSSEAuth);
$objSoapVarWSSEToken = new SoapVar($objWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS); 
$objSoapVarHeaderVal=new SoapVar($objSoapVarWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'Security', $strWSSENS);

$objSoapVarWSSEHeader = new SoapHeader($strWSSENS, 'Security', $objSoapVarHeaderVal,true); 


$client = new SoapClient(
    //"http://app.udem.edu.co/PrueServiciosAcademicos/wsAcademicoSoapHttpPort?WSDL", 
    "cliente.wsdl", 
    array(
        'login' => 'serviciosAcadem', 
        'password'=>'Ws_2011_',
        'authentication' => SOAP_AUTHENTICATION_DIGEST,
        'trace'=>1
    )
);


$client->__setSoapHeaders(array($objSoapVarWSSEHeader)); 

try {
//$client->consultarAsignaturasXUOC('wsservacad', '4cyn=,Bu', '06900300000', '3', 'CAT_SERV_ACADEM');
$res = $client->__soapCall('consultarAsignaturasXUOC', array('wsservacad', '4cyn=,Bu', '06900300000', '3', 'CAT_SERV_ACADEM')); 

}
catch (Exception $e) {

echo($client->__getLastRequestHeaders()."<br>");
		echo($client->__getLastRequest()."<br>");				
		echo($client->__getLastResponseHeaders());
echo "<hr>";
var_dump($e);
        /*
$h = $client->__getLastRequest();
print_r($h);
echo "<hr>";
var_dump($e);*/
}
exit;




admin_externalpage_setup('moosisca_newspacerequest');
admin_externalpage_print_header();

  $displaylist = array();
  $parentlist = array();

  $displaylist[0] = get_string('top');
  make_categories_list($displaylist, $parentlist);
  
  echo <<<EOF
    <script type="text/javascript">
      function showHideCategoryTextbox(categoryId){
        var h1 = document.getElementById('hidC1_' + categoryId);
        var h2 = document.getElementById('hidC2_' + categoryId);
        
        var tr = document.getElementById('divTitles');
        var div = document.getElementById('divCourse');
        var txt = document.getElementById('txtCourseName');
        var cbo = document.getElementById('cboCoursesWs');
        var cboType = document.getElementById('cboSpaceType');
        
        if(0 && (h1.value != '' || h2.value != '')){
          txt.style.display = 'none';
          cbo.style.display = '';
          cboType.style.display = '';
          tr.style.display = '';
          div.style.display = '';
        }
        else{
          txt.style.display = '';
          cbo.style.display = 'none';
          cboType.style.display = '';
          tr.style.display = '';
          div.style.display = '';
        }
      }
      
      function validateAndSend(){
        var txt = document.getElementById('txtCourseName');
        var cbo = document.getElementById('cboCoursesWs');
        var hid = document.getElementById('hidFullName');
        
        if(txt.style.display != 'none' && txt.value == ''){
          alert("
EOF;
echo get_string('fieldRequired', 'report_moosisca', $a = get_string('courseName', 'report_moosisca'));
  echo <<<EOF
          ");
          return;
        }
        else if(cbo.style.display != 'none'){
          hid.value = cbo.options[cbo.selectedIndex].text;
        }
        
        document.newspacerequestform.submit();
      }
    </script>
EOF;

  echo '<form name="newspacerequestform" id="newspacerequestform" method="post" action="newspacerequest.php">';
  echo '<input type="hidden" name="sesskey" value="'.sesskey().'"/>';
  echo '<input type="hidden" name="hidFullName" id="hidFullName" value=""/>';
  
  print_heading(get_string('newspacerequest', 'report_moosisca'));
  
  echo '<table class="generalbox editcourse boxaligncenter">';
  
  $displaylist = get_categories_tree();
  
  //print_r($displaylist);

  $html = print_category_edit(NULL, $displaylist, $parentlist);
  echo $html;

  echo '</table>';
  
  $spaceType = '<select id="cboSpaceType" name="cboSpaceType" style="display:none; margin-top: 5px;">';
  $spaceType .= '<option value="R">' . get_string('spaceType.Repository', 'report_moosisca') . '</option>';
  $spaceType .= '<option value="S">' . get_string('spaceType.SupportToClass', 'report_moosisca') . '</option>';
  $spaceType .= '<option value="B">' . get_string('spaceType.Blended', 'report_moosisca') . '</option>';
  $spaceType .= '</select>';
  
  $courses = '<select id="cboCoursesWs" name="cboCoursesWs" style="display:none">';
  $courses .= '<option value="cur1">Curso 1</option>';
  $courses .= '<option value="cur2">Curso 2</option>';
  $courses .= '<option value="cur3">Curso 3</option>';
  $courses .= '</select>';  

  echo '<div id="divCourse" style="width:600px; margin:auto; display:none">';
  echo ' <div id="divTitles" style="display:none;">';
  echo '  <span>';
  echo get_string('courseName', 'report_moosisca') . ': ';
  echo '  </span>';
  echo '  <span>';
  echo '    <input id="txtCourseName" name="txtCourseName" type="text" style="display:none" size="60" maxlength="100" />';
  echo $courses;
  echo '  </span>';
  echo ' </div>';
  echo ' <div>';
  echo '  <span>';
  echo get_string('spaceType', 'report_moosisca') . ': ';
  echo '  </span>';  
  echo '  <span>' . $spaceType . '</span>';
  echo ' </div>';
  echo '</div><br/>';
  
  echo '<div class="buttons">';
  echo '  <div class="button">';
  echo '<input type="button" onclick="validateAndSend()" name="btnSave" value="'.get_string('save', 'report_moosisca').'" />';
  echo '  </div>';
  echo '</div>';
  echo '</form>';
  
  admin_externalpage_print_footer();

function validation($courseName) {
  $errors = "";
  $foundcourses = null;

  if (!empty($courseName)) {
    $foundcourses = get_records('course', 'shortname', $courseName);
  }

  if (!empty($foundcourses)) {
    foreach ($foundcourses as $foundcourse) {
      $foundcoursenames[] = $foundcourse->fullname;
    }
    $foundcoursenamestring = implode(',', $foundcoursenames);

    $errors = get_string('shortnametaken', '', $foundcoursenamestring);
  }

  return $errors;
}
  
function print_category_edit($category, $displaylist, $parentslist, $depth=-1) {

    $hascontent = false;
    $html = '';
/// Recursive function to print all the categories ready for editing

  global $CFG, $USER;

  if (!empty($category)) {

      if (!isset($category->context)) {
          $category->context = get_context_instance(CONTEXT_COURSECAT, $category->id);
      }
      
      $html .= '<tr>';
      
      if($category->category_id != '')
      {
        $hascontent = true;
        $html .= '<td><input type="radio" id=radCategory name="radCategory" value="'.$category->id.'" onClick="showHideCategoryTextbox('.$category->id.')"  />';
        $html .= '  <input type="hidden" id="hidC1_'.$category->id.'" name="hidC1_'.$category->id.'" value="'.$category->cod1.'" />';
        $html .= '  <input type="hidden" id="hidC2_'.$category->id.'" name="hidC2_'.$category->id.'" value="'.$category->cod2.'" />';
        $html .= '</td>';
        
      }
      else 
      {
        $html .= '<td>&nbsp;</td>';
      }

      $html .= '<td align="left" class="name">';
      for ($i=0; $i<$depth;$i++) {
          $html .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
      }
      $linkcss = $category->visible ? '' : ' class="dimmed" ';
      $html .= format_string($category->name);
      $html .= '</td>';
      $html .= '</tr>';
  } else {
      $category->id = '0';
  }

  if ($categories = get_categories_moosisca($category->id)) {   // Print all the children recursively
    $countcats = count($categories);
    $count = 0;
    foreach ($categories as $cat) {
      $count++;
      if ($count == $countcats) {
          $last = true;
      }

      $returnhtml = print_category_edit($cat, $displaylist, $parentslist, $depth+1);
      
      if (!empty($returnhtml)){
        $html .= $returnhtml;
        $hascontent = true;
      }
    }
  }
  
  if ($hascontent) {
    return $html;
  }
  else {
    return null;
  }
}

/*
function print_category_edit($category, $displaylist, $parentslist, $depth=-1) {

    $hascontent = false;
    $html = '';
/// Recursive function to print all the categories ready for editing

//print_r($category);
//echo "<br>";

  global $CFG, $USER;

  if (!empty($category)) {

      if (!isset($category->context)) {
          $category->context = get_context_instance(CONTEXT_COURSECAT, $category->id);
      }
      
      echo '<tr>';
      
      if($category->category_id != '')
      {
        $hascontent = true;
        echo '<td><input type="radio" id=radCategory name="radCategory" value="'.$category->id.'" onClick="showHideCategoryTextbox('.$category->id.')"  />';
        echo '  <input type="hidden" id="hidC1_'.$category->id.'" name="hidC1_'.$category->id.'" value="'.$category->cod1.'" />';
        echo '  <input type="hidden" id="hidC2_'.$category->id.'" name="hidC2_'.$category->id.'" value="'.$category->cod2.'" />';
        echo '</td>';
        
      }
      else 
      {
        echo '<td>&nbsp;</td>';
      }

      echo '<td align="left" class="name">';
      for ($i=0; $i<$depth;$i++) {
          echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
      }
      $linkcss = $category->visible ? '' : ' class="dimmed" ';
      echo format_string($category->name);
      echo '</td>';
      echo '</tr>';
  } else {
      $category->id = '0';
  }

  if ($categories = get_categories_moosisca($category->id)) {   // Print all the children recursively
    $countcats = count($categories);
    $count = 0;
    foreach ($categories as $cat) {
      $count++;
      if ($count == $countcats) {
          $last = true;
      }

      print_category_edit($cat, $displaylist, $parentslist, $depth+1);
    }
  }  
}
*/
?>